"""
图片引用处理器
处理Markdown和HTML格式的图片引用，包括图片验证、优化和格式转换
"""

import os
from dataclasses import dataclass

from loguru import logger

from mdtool.image.processor import optimize_image
from mdtool.util import check_image_url, is_valid_image

# 图片处理的常量定义
MAX_SIZE_KB = 2048  # 最大文件大小（KB）
MAX_DIMENSION = 2000  # 最大图片尺寸（像素）
VALID_FORMATS = ["jpeg", "jpg", "png", "gif"]  # 支持的图片格式


@dataclass
class ImageReference:
    url_in_text: str
    original_path: str
    target_path: str = ""
    existed: bool = True
    external: bool = False
    alt_text: str = ""
    is_html: bool = False
    publish_type: str = "mdtool"
    size: int = 0
    format: str = ""
    width: int = 0
    height: int = 0

    def __post_init__(self):
        """Initialize additional attributes after instance creation"""
        if self.original_path and os.path.exists(self.original_path):
            self._analyze_image()

    @property
    def path(self) -> str:
        """Get the path of the image. For backward compatibility."""
        return self.original_path

    @property
    def original_text(self) -> str:
        """Get the original text of the image reference. For backward compatibility."""
        return self.url_in_text

    def _analyze_image(self) -> None:
        """Analyze image properties including format, size, and dimensions"""
        try:
            # 使用Python Imaging Library (PIL)分析图片
            from PIL import Image

            # 获取文件大小
            self.size = os.path.getsize(self.original_path)

            # 获取图片尺寸和格式
            with Image.open(self.original_path) as img:
                self.width, self.height = img.size
                self.format = img.format.lower()

            if not self.format:
                logger.warning(f"无法确定图片格式: {self.original_path}")
                return

            logger.debug(
                f"图片分析结果 - 路径: {self.original_path}, 格式: {self.format}, "
                f"大小: {self.size/1024:.1f}KB, 尺寸: {self.width}x{self.height}"
            )

        except ImportError:
            logger.warning("PIL库未安装，无法分析图片属性")
        except Exception as e:
            logger.warning(f"分析图片时出错: {str(e)}")

    def optimize(self) -> bool:
        """Optimize image to meet all requirements

        Returns:
            bool: True if optimization was successful or not needed
        """
        if self.url_in_text.startswith("http"):
            logger.warning("无法优化远程图片")
            return False

        if not os.path.exists(self.original_path):
            logger.error(f"图片文件不存在: {self.original_path}")
            return False

        # 分析图片属性（如果还没有分析）
        if not hasattr(self, "format") or not self.format:
            self._analyze_image()

        # 检查是否需要优化
        needs_optimization = (
            self.format not in VALID_FORMATS
            or self.size > MAX_SIZE_KB * 1024
            or self.width > MAX_DIMENSION
            or self.height > MAX_DIMENSION
        )

        if not needs_optimization:
            logger.debug(f"图片无需优化: {self.original_path}")
            return True

        # 执行优化
        if optimize_image(self.original_path):
            # 重新分析优化后的图片
            self._analyze_image()
            logger.debug(f"图片优化成功: {self.original_path}")
            return True
        else:
            logger.warning(f"图片优化失败: {self.original_path}")
            return False

    def check(self, auto_optimize: bool = True) -> bool:
        """Check if the image is valid and meets requirements

        Args:
            auto_optimize: Whether to automatically optimize the image if it doesn't meet requirements

        Returns:
            bool: True if image is valid and meets all requirements
        """
        # 检查图片是否存在
        if self.url_in_text.startswith("http"):
            ret = check_image_url(self.url_in_text)
            if not ret:
                logger.error(f"无效的图片URL: {self.url_in_text}")
                return False
            return True
        else:
            ret = is_valid_image(self.original_path)
            if not ret:
                logger.error(f"图片文件不存在: {self.original_path}")
                return False

        # 如果图片存在，分析其属性
        if not hasattr(self, "format") or not self.format:
            self._analyze_image()

        # 验证图片格式
        if self.format not in VALID_FORMATS:
            logger.error(
                f"不支持的图片格式 {self.format}，支持的格式: {', '.join(VALID_FORMATS)}"
            )
            if auto_optimize:
                logger.info(f"尝试自动优化图片: {self.original_path}")
                return self.optimize()
            return False

        # 验证图片大小
        if self.size > MAX_SIZE_KB * 1024:
            logger.warning(
                f"图片大小超过限制: {self.size/1024/1024:.1f}MB > {MAX_SIZE_KB/1024}MB\n图片位置: {self.original_path}"
            )
            if auto_optimize:
                logger.debug(f"尝试自动优化图片: {self.original_path}")
                return self.optimize()
            return False

        # 验证图片尺寸
        if self.width > MAX_DIMENSION or self.height > MAX_DIMENSION:
            logger.warning(
                f"图片尺寸过大: {self.width}x{self.height}，建议不超过{MAX_DIMENSION}x{MAX_DIMENSION}"
            )
            if auto_optimize:
                logger.info(f"尝试自动优化图片: {self.original_path}")
                return self.optimize()
            # 不返回False，只是警告

        return True
